package com.yaowk.sfp.system.server.controller;

import com.yaowk.sfp.common.base.model.result.NavMenu;
import com.yaowk.sfp.system.api.AuthApi;
import com.yaowk.sfp.system.api.model.Menu;
import com.yaowk.sfp.system.api.model.Role;
import com.yaowk.sfp.system.api.model.User;
import com.yaowk.sfp.system.server.service.IMenuService;
import com.yaowk.sfp.system.server.service.IRoleService;
import com.yaowk.sfp.system.server.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController("SystemAuthController")
@Api(tags = "登录信息")
public class AuthController implements AuthApi {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private com.yaowk.sfp.security.api.AuthApi authApi;

    @Override
    @ApiOperation("登录用户信息")
    public User user() {
        return userService.findById(authApi.getUserId());
    }

    @Override
    @ApiOperation("登录用户角色")
    public List<Role> role() {
        List<Role> roles = roleService.findAllByUserId(authApi.getUserId());
        return roles;
    }

    @Override
    @ApiOperation("导航栏")
    public Set<NavMenu> navigation() {
        List<Menu> menus = menuService.findAllByUserId(authApi.getUserId());

        NavMenu<Menu> navMenu = new NavMenu();
        Menu menu = menuService.findById(1L);
        navMenu.setValue(menu);
        findMenuChildren(menus, navMenu);

        return navMenu.getChildren();
    }

    @Override
    @ApiOperation("用户权限")
    public List<Long> permission(@PathVariable Long userId) {
        return userService.findPermissionsByUserId(userId);
    }

    /**
     * 格式化导航栏返回值
     *
     * @param menus
     * @param navMenu
     */
    private void findMenuChildren(List<Menu> menus, NavMenu<Menu> navMenu) {
        Long parentId = navMenu.getValue().getId();
        for (Menu menu : menus) {
            if (parentId.equals(menu.getParentId())) {
                NavMenu<Menu> n = new NavMenu();
                n.setValue(menu);
                boolean result = navMenu.getChildren().add(n);
                if (result) {
                    findMenuChildren(menus, n);
                }
            }
        }
    }
}
